class UrlController < ApplicationController
    include AuthenticatedSystem
    include UrlHelper
    before_filter :login_required  

    def new
        @link = Link.new
    end
  
    def create
        # store the url
        now = Time.now
        params[:link][:last_collected_at] = now
        params[:link][:last_collected_user] = session[:user]
        @link = Link.new(params[:link])
        url = @link.body
        if @link.exist?
            # update
            if url_saved_by_user(url)
                flash[:error] = "您已经添加了该链接"
                redirect_to :action => 'new'
                return
            else
                link_to_save = get_url_by_website(url)
                link_to_save.tag_list = params[:link][:taglist]               #modify  by mao mao 
                link_to_save.save
                link = get_url_by_website(url)
                link.update_attributes(params[:link])
                uu = create_users_urls_with_link(link, session[:user])
                uu.tag_list = params[:link][:taglist]
                uu.save
            end
        else
            # create
            @link.tag_list = params[:link][:taglist]               #modify  by mao mao 
            @link.save
            uu = create_users_urls_with_link(@link, session[:user])
            uu.tag_list = params[:link][:taglist]
                                       
            
            uu.save
        end
        # @link.save
        # store the relations of user and url
        # store tags
        flash[:notice] = "添加成功!"
        redirect_to :action => 'new'
    end
  
    def list
        @user = User.find(session[:user])
        @users_urls = UsersUrls.find(:all, :conditions => ["user_id=?", session[:user]], :order => 'collected_at DESC')
    end
    
    def add
        @link = Link.find(params[:id])
        uu = UsersUrls.find(:first, :conditions => ["url_id=?", params[:id]], :order => 'collected_at DESC')
        @link.taglist = uu.tag_list
    rescue
        flash[:error] = "该链接不存在!"
        redirect_to :action => 'new'
    end
    
    def show
        @link = Link.find(params[:url_id])
    end

    def comment
        @link = Link.find(params[:comment][:url_id])
        comment = Comment.new
        comment.comment = params[:comment][:comment]
        comment.commentable_id = params[:comment][:url_id]
        comment.commentable_type = "Link"
        comment.user_id = session[:user]
        @link.comments << comment
        render :partial => "comments", :link => @link
    end
    
    def users
        @link = Link.find(params[:url_id])
        @users = User.find_by_sql("select * from users where id in (select user_id from users_urls where url_id = #{params[:url_id]})") 
    end
end
